<template>
    <div class="case">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-copy"></i> 新增用例</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-form ref="form" :model="form" :rules="rules">
            <el-tabs v-model="message" @tab-click="handleClick">
                <!-- 基本信息|数据依赖 -->
                <el-tab-pane :label="`基本信息|数据依赖`" name="0">
                        <el-form-item label="用例名称" prop="name">
                            <el-input v-model="form.name" style="width:500px"></el-input>
                        </el-form-item>
                        <el-form-item label="所属项目" prop="project_id">
                            <el-select v-model="form.project_id" placeholder="选择项目" @change="getModuleByProject" style="width:500px;">
                                <el-option v-for="project in projects"
                                    :key="project.id"
                                    :label="project.name"
                                    :value="project.id"
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="所属模块" prop="modular">
                            <el-select v-model="form.modular" placeholder="选择模块" style="width:500px">
                                <el-option v-for="time in modulars"
                                    :key="time.id"
                                    :label="time.name"
                                    :value="time.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="选择配置" style="margin-left:10px">
                            <el-select v-model="form.config" placeholder="请选择" style="width:500px">
                                <el-option v-for="conf in configures"
                                    :key="conf.id"
                                    :label="conf.name"
                                    :value="conf.id">
                                </el-option>
                            </el-select>
                        </el-form-item> -->
                        <el-transfer 
                            v-model="form.caseSteps"
                            :props="{key: 'id',label: 'name'}"
                            :data="allSteps"
                            :titles="['所有用例', '已选前置用例']">
                        </el-transfer>
                </el-tab-pane>

                <!-- 请求信息 -->
                <el-tab-pane :label="` 请求信息 `" name="1">
                    <el-select v-model="form.method" placeholder="请求方法">
                        <el-option
                            v-for="item in methodlist"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                    <el-input placeholder="URL" v-model="form.url" style="width: 600px; margin-left: 20px" prop="url">
                        <template slot="prepend">URL</template>
                    </el-input>
                    <el-select v-model="datatypes" placeholder="参数类型" style="margin-left: 20px; margin-bottom: 20px;" @change="jsonIsData">
                        <el-option
                            v-for="item in datatype"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                    <el-form-item label="">
                        <el-button type="primary" @click="addTableRow('apiHeaders')">添加Headers</el-button>
                        <base-extract-table :tableData="form.apiHeaders" @removeRowByIndex="removeHeadersByIndex"></base-extract-table>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" @click="addTableRow('apiParams')">添加params</el-button>
                        <base-extract-table :tableData="form.apiParams" @removeRowByIndex="removeParamsByIndex"></base-extract-table>
                    </el-form-item>
                    <el-form-item label="" v-if="reqdatat">
                        <el-button type="primary" @click="addTableRow('apiPostData')">添加data</el-button>
                        <base-extract-table :tableData="form.apiPostData" @removeRowByIndex="removePostDataByIndex"></base-extract-table>
                    </el-form-item>
                    <!-- json数据 -->
                    <el-form-item v-else label="json编辑器">
                        <CodeEditor
                            :options="options"
                            :value="content"
                            @contentChange="contentChange"
                            style="height: 350px; width: 95%; margin-top:15px;"
                            >
                        </CodeEditor>
                    </el-form-item>
                </el-tab-pane>
                <!-- 提取数据|校验数据 -->
                <el-tab-pane :label="` 提取数据|校验数据 `" name="2">
                    <el-form-item label="">
                        <el-button type="primary" @click="addTableRow('extract')">添加提取数据(extract)</el-button>
                        <base-extract-table :tableData="form.extract" @removeRowByIndex="removeExtractByIndex"></base-extract-table>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" @click="addTableRow('validate')">添加校验数据(validate)</el-button>
                        <base-validate-table :tableData="form.validate" @removeRowByIndex="removeValidateByIndex"></base-validate-table>
                    </el-form-item>
                </el-tab-pane>
                <!-- 变量|参数化 -->
                <el-tab-pane :label="` 变量|参数化  `" name="3">
                    <el-form-item label="">
                        <el-button type="primary" @click="addTableRow('parameters')">添加参数化数据(parameters)</el-button>
                        <base-extract-table :tableData="form.parameters" @removeRowByIndex="removeParametersByIndex"></base-extract-table>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" @click="addTableRow('variables')">添加全局变量(variables)</el-button>
                        <base-extract-table :tableData="form.variables" @removeRowByIndex="removeVariablesByIndex"></base-extract-table>
                    </el-form-item>
                </el-tab-pane>
            </el-tabs>
                <el-form-item style="margin-top: 50px">
                    <el-button type="primary" @click="save('form')">保存编辑</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    import baseVariablesTable from '../SmallParts/baseVariablesTable'
    import baseValidateTable from '../SmallParts/baseValidateTable'
    import baseExtractTable from '../SmallParts/baseExtractTable'
    import {removeInArrayByIndex} from '../../utils/common'
    import CodeEditor from "../common/CodeEditor";
    import { projects_names } from '../../api/api';
    import { project_in_modulars, config_in_project } from '../../api/api';
    import { add_case } from '../../api/api';
    import { pcase_in_project } from '../../api/api'
    import { read_case } from '../../api/api'
    import { edit_case } from '../../api/api'
    
    export default {
        name: 'case',
        components: { CodeEditor, baseVariablesTable, baseValidateTable, baseExtractTable },
        data() {
            return {
                message: '0',
                showHeader: false,
                content:'',
                methodvalue: 'GET',
                projects: [],
                modulars: [],
                // configures: [],
                reqdatat: true,
                allSteps: [],
                selectheaderlistRow: [],
                selectdatalistRow: [],
                methodlist: [{
                    value: 'GET',
                    label: 'GET'
                }, {
                    value: 'POST',
                    label: 'POST'
                }, {
                    value: 'PUT',
                    label: 'PUT'
                }, {
                    value: 'DELETE',
                    label: 'DELETE'
                }, {
                    value: 'PATCH',
                    label: 'PATCH',
                }],
                datatypes: 'Data',
                datatype: [{
                    value: 'Data',
                    label: 'Data'
                },{
                    value: 'Json',
                    label: 'Json'
                }],
                relativePros: [],
                options: {
                    language: "json",
                    theme: 'vs-dark',
                    readOnly: false
                },
                rules: {
                    name: [
                        { required: true, message: '请用例名称', trigger: 'blur' },
                        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                    ],
                    project_id: [
                        { required: true, message: '请选择所属项目', trigger: 'change' }
                    ],
                    modular: [
                        { required: true, message: '请选择所属模块', trigger: 'change' }
                    ],
                    url: [
                        { required: true, message: '请输入URL', trigger: 'blur' }
                    ],
                },
                form: {
                    project_id:'',
                    modular:'',
                    // config: '',
                    name: '',
                    url: '',
                    method: 'GET',
                    caseSteps: [],
                    // 格式为: [{"keyName":"", "valueType":"", "value":""}, {, , }...]
                    apiHeaders: [],
                    // 格式为: [{"keyName":"", "valueType":"", "value":""}, {, , }...]
                    apiParams: [],
                    // 格式为: [{"keyName":"", "valueType":"", "value":""}, {, , }...]
                    apiPostData: [],
                    // 格式为: [{"keyName":"", "valueType":"", "value":""}, {, , }...]
                    apiJson: [],
                    variables: [],
                    // 格式为: [{"keyName":"token", "value":"content.token"}, {, , }...]
                    extract: [],
                    // 格式为: [{"keyName":"status_code", "comparator":"equals", "valueType":"int", "value":"200"}], {, , }...
                    validate: [],
                    parameters: []
                }
            }
        },
        created() {
            this.getProjects();
            this.getData();
        },
        methods: {
            //获取被编辑数据的原有数据
            getData(){
                read_case(this.$route.query.id)
                    .then(response =>{
                        this.form.name = response.data.testcase_name
                        this.form.project_id = response.data.selected_project_id
                        this.getModuleByProject(this.form.project_id)
                        this.form.modular = response.data.selected_modular_id
                        // if (response.data.selected_configure_id){
                        //     this.from.config = response.data.selected_configure_id
                        // }
                        this.form.caseSteps = response.data.selected_testcase_id
                        this.form.method = response.data.method
                        this.form.url = response.data.url
                        this.form.apiHeaders = response.data.header
                        this.form.apiParams = response.data.param
                        if(response.data.json != 'null' ){
                            this.content = JSON.stringify(JSON.parse(response.data.json), null, "\t")
                            this.contentChange(this.content)
                            this.datatypes = "Json"
                        }else{
                            this.form.apiPostData = response.data.data
                        }
                        this.form.extract = response.data.extract
                        this.form.validate = response.data.validate
                        this.form.parameters = response.data.parameters
                        if(response.data.variables){
                            this.form.variables = response.data.variables
                        }
                        this.$message.success("获取用例原有数据成功");

                    })
                    .catch(error =>{
                        this.$message.error('获取用例原有数据失败');
                    })
            },
            // 获取项目列表
            getProjects() {
                projects_names()
                    .then(response => {
                        this.projects = response.data;
                    })
                    .catch(error =>{
                        this.$message.error('获取项目列表失败');
                    });
            },
            // 获取某项目下的所有模块和所有用例还有配置
            getModuleByProject(id) {
                project_in_modulars(id)
                    .then(response => {
                        this.modulars = response.data
                    })
                    .catch(error => {
                        this.$message.error('根据项目id获取模块失败')
                    }),
                // config_in_project(id)
                //     .then(response => {
                //         this.configures = response.data
                //     })
                //     .catch(error => {
                //         this.$message.error('根据项目id获取配置失败')
                //     }),
                pcase_in_project(id)
                    .then(response => {
                        this.allSteps = response.data
                    })
                    .catch(error => {
                        this.$message.error('根据模块id获取用例失败')
                    })
            },

            // 判断是请求参数json还是data
            jsonIsData(datatype){
                if(datatype=='Data'){
                    this.reqdatat=true
                }else{
                    this.reqdatat=false
                }
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            // 保存用例编辑
            save: function(formData){
                this.$refs[formData].validate((valid) => {
                    if (valid) {
                        //需要格式转换
                        let postForm = this.formTransform();
                        edit_case(this.$route.query.id,postForm)
                            .then(response => {
                                this.$message.success('数据修改成功');
                                this.$router.push({
                                    path: '/CaseList',
                                })
                            })
                            .catch(error => {
                                this.$message.error('数据修改失败');
                            })
                    } else {
                        window.console.log('表单格式校验失败!');
                        this.$message.error('请输入必填项！');
                        return false;
                    }
                });
            },
            contentChange(value) {
                this.form.apiJson = JSON.parse(value.replace(/\s*/g,""))
            },
            handleClick(tab){
                if(tab.name == "1"){
                    this.jsonIsData(this.datatypes)
                }
            },
            addTableRow(name){
                if(name === "apiHeaders"){
                    this.form.apiHeaders.push({});
                }
                else if (name === "apiParams"){
                    this.form.apiParams.push({});
                }
                else if (name === "apiPostData"){
                    this.form.apiPostData.push({});
                }
                else if (name === "extract"){
                    this.form.extract.push({});
                }
                else if (name === "validate"){
                    this.form.validate.push({});
                }
                else if (name === "parameters"){
                    this.form.parameters.push({});
                }
                else if (name === "variables"){
                    this.form.variables.push({});
                }
                else {
                    window.console.log("无法识别: " + name);
                }
            },
            // 移除headers单行
            removeHeadersByIndex(array, removeIndex){
                this.form.apiHeaders = removeInArrayByIndex(array, removeIndex);
            },
            // 移除params单行
            removeParamsByIndex(array, removeIndex){
                this.form.apiParams = removeInArrayByIndex(array, removeIndex);
            },
            // 移除postData单行
            removePostDataByIndex(array, removeIndex){
                this.form.apiPostData = removeInArrayByIndex(array, removeIndex);
            },
            // 移除variables单行
            removeVariablesByIndex(array, removeIndex){
                this.form.variables = removeInArrayByIndex(array, removeIndex);
            },
            // 移除extract单行
            removeExtractByIndex(array, removeIndex){
                this.form.extract = removeInArrayByIndex(array, removeIndex);
            },
            // 移除validate单行
            removeValidateByIndex(array, removeIndex){
                this.form.validate = removeInArrayByIndex(array, removeIndex);
            },
            // 移除parameters单行
            removeParametersByIndex(array, removeIndex){
                this.form.parameters = removeInArrayByIndex(array, removeIndex);
            },
            // 发送请求前的格式转换
            formTransform: function () {
                //深拷贝
                let postForm = JSON.parse(JSON.stringify(this.form));
                let casedata = {}
                casedata["name"] = postForm.name
                casedata["modular"] = {"pid":postForm.project_id,"mid":postForm.modular}
                casedata["include"] = {"config":null, "testcases":postForm.caseSteps}
                casedata["author"] = "刘翔"
                casedata["request"] = {"test":{"name":postForm.name}}
                casedata["request"]["test"] = {"request":{"url":postForm.url}}
                casedata["request"]["test"]["request"]["method"] = postForm.method
                casedata["request"]["test"]["name"] = postForm.name
                if (postForm.apiHeaders.length != 0){
                    let headers = {}
                    for (let i =0; i < postForm.apiHeaders.length; i++) {
                        headers[postForm.apiHeaders[i].keyName] = postForm.apiHeaders[i].value
                    };
                    casedata["request"]["test"]["request"]["headers"] = headers
                }
                if (postForm.apiParams.length != 0){
                    let params = {};
                    for (let i =0; i < postForm.apiParams.length; i++) {
                        params[postForm.apiParams[i].keyName] = postForm.apiParams[i].value
                    }
                    casedata["request"]["test"]["request"]["params"] = params
                }
                if (postForm.apiPostData.length != 0){
                    let pdata ={};
                    for (let i =0; i < postForm.apiPostData.length; i++) {
                        pdata[postForm.apiPostData[i].keyName] = postForm.apiPostData[i].value
                    }
                    casedata["request"]["test"]["request"]["data"] = pdata
                }
                if (postForm.apiJson.length != 0){
                    casedata["request"]["test"]["request"]["json"] = postForm.apiJson
                }
                if (postForm.validate.length != 0){
                    let validate = []
                    for (let i =0; i < postForm.validate.length; i++) {
                        if(postForm.validate[i].valueType == "int"){
                            var intvalue = parseInt(postForm.validate[i].value)
                        }else if(postForm.validate[i].valueType == "float"){
                            intvalue = parseFloat(postForm.validate[i].value)
                        }else{
                            intvalue = postForm.validate[i].value
                        }
                        validate.push({
                            check:postForm.validate[i].keyName,
                            comparator: postForm.validate[i].comparator,
                            expected: intvalue,
                        })
                    }
                    casedata["request"]["test"]["validate"] = validate
                }
                if (postForm.extract.length != 0){
                    let extract = []
                    for (let i =0; i < postForm.extract.length; i++) {
                        let arr = {}
                        arr[postForm.extract[i].keyName] = postForm.extract[i].value,
                        extract.push(arr)
                    }
                    casedata["request"]["test"]["extract"] = extract
                }
                if (postForm.parameters.length != 0){
                    let parameters = []
                    for (let i =0; i < postForm.parameters.length; i++) {
                        let arr = {}
                        arr[postForm.parameters[i].keyName] = postForm.parameters[i].value,
                        parameters.push(arr)
                    }
                    casedata["request"]["test"]["parameters"] = parameters
                }
                if (postForm.variables.length != 0){
                    let parameters = []
                    for (let i =0; i < postForm.variables.length; i++) {
                        let arr = {}
                        arr[postForm.variables[i].keyName] = postForm.variables[i].value,
                        variables.push(arr)
                    }
                    casedata["request"]["test"]["variables"] = variables
                }
                casedata["include"] = JSON.stringify(casedata["include"])
                casedata["request"] = JSON.stringify(casedata["request"])
                return casedata
            }
        },
        computed: {}
    }

</script>

<style>

.container {
    text-align: left;
    padding: 10px;
}
el-form-item{
    margin-top: 20px;
}

</style>

